//
//  ComposeViewController.swift
//  Weibo
//
//  Created by Heaven on 15/7/6.
//  Copyright © 2015年 Heaven. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

/// 微博文字的最大长度
private let statusMaxLength = 140

class ComposeViewController: UIViewController, UITextViewDelegate {

    // 懒加载表情键盘控制器
    private lazy var emoticonKeyboardVC: EmoticonViewController = EmoticonViewController { [unowned self] (emoticon)  in
        self.textView.insertEmoticon(emoticon)
    }
   
    /// 切换表情视图
    func inputEmoticon() {

        // 切换之前 先关闭
        textView.resignFirstResponder()
        
        // 如果输入视图是nil 默认使用系统键盘
        // 键盘输入视图
        textView.inputView = (textView.inputView == nil) ? emoticonKeyboardVC.view : nil
    
        // 重新设置焦点
        textView.becomeFirstResponder()
    }
    
    /// 选择照片
    func selectPhoto() {
        print(__FUNCTION__)
    }
    
    /// 关闭
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发布微博
    func sendStatus() {
        // 判断是否有内容
        if textView.emoticonText().characters.count <= 0 {
            return
        }
        
        // 判断文本是否过长
        if textView.emoticonText().characters.count > statusMaxLength {
            SVProgressHUD.showInfoWithStatus("文本内容过长!", maskType: SVProgressHUDMaskType.Black)
            return
        }
        
        SVProgressHUD.show()
        NetworkTools.sharedNetworkTools().postStatus(textView.emoticonText()) { (error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            // 发布成功关闭窗口
            self.close()
        }
    }
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.randomColor()
        prepareUI()
    }
    
    override func viewDidLoad() {
        // 添加子控制器
        addChildViewController(emoticonKeyboardVC)
        
        // 设置代理
        textView.delegate = self
        
        // 注册键盘监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }

    // 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // TODO: -需要再看 理解一下！！
    /// 本地键盘切换标记 - 以下函数专用
    private var localKeyboardFlag = false
    ///  键盘通知变化处理函数
    func keyboardChanged(notification: NSNotification) {
        
        // 1. 拿到 userInfo 中的 endUser Rect
        // OC 中结构体保存在字典中，保存的类型是 NSValue，swift中同样
        let rect = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 键盘动画时长
        var duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        // 取 UIKeyboardIsLocalUserInfoKey，如果为0，不做动画
        if notification.userInfo!["UIKeyboardIsLocalUserInfoKey"] != nil {
        let local = notification.userInfo!["UIKeyboardIsLocalUserInfoKey"]!.boolValue
        
        if !local {
            localKeyboardFlag = true
            return
        
            }
        }
        // 根据 localKeyboardFlag 设置动画时长
        duration = localKeyboardFlag ? 0 : duration
        localKeyboardFlag = false
        
        // 2. 设置键盘高度
        toolBarBottomCons?.constant = -(view.bounds.height - rect.origin.y)
        
        // 3. 动画
        UIView.animateWithDuration(duration) {
            self.view.layoutIfNeeded()
        }
    }

    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(animated: Bool) {
        textView.resignFirstResponder()
    }
    
    // MARK: - textViewDidChange
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
   
        // 判断文字长度
        print(textView.emoticonText().characters.count)
        let len = statusMaxLength - textView.emoticonText().characters.count
        lengthLabel.text = (len > 10 ) ? "" : String(len)
        lengthLabel.textColor = len > 0 ? UIColor.lightGrayColor() : UIColor.redColor()
        
    }
    
    // MARK: - 准备UI
    private func prepareUI() {
        
        //automaticallyAdjustsScrollViewInsets = false
        
        prepareNavigationBar()
        prepareTextView()
        prepareToolBar()
        prepareOthers()
    }
    
    /// 准备其他控件
    private func prepareOthers() {
        view.addSubview(lengthLabel)
        lengthLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -12, y: -12))
    }
    
    /// 准备toolBar
    private func prepareToolBar() {
    
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)

        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        // 所有按钮的数组
        var items = [UIBarButtonItem]()
        
        // 设置按钮 - 问题：图片名称(高亮图片) / 监听方法
        for settings in itemSettings {
            items.append(UIBarButtonItem(imageName: settings["imageName"]!, highlightedImageName: nil, target: nil, actionName: settings["action"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
       
        // 删除末尾的弹簧
        items.removeLast()

        // 给 toolBar 设置 items
        toolBar.items = items
        
        // 添加到View上
        view.addSubview(toolBar)
        let cons = toolBar.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: nil)
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["toolBar": toolBar]))
        
        // 记录toolBar 底部约束
        toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
    }
    
    private func prepareTextView() {
        view.addSubview(textView)
        
        textView.font = UIFont.systemFontOfSize(18)
        
        textView.ff_AlignInner(ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(ff_AlignType.TopRight, referView: toolBar, size: nil)
        
        // 设置垂直滚动
        textView.alwaysBounceVertical = true
        // 滚动关闭键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        // 设置 占位标签
        placeHolderLabel.text = "分享新鲜事..."
        placeHolderLabel.sizeToFit()
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.ff_AlignInner(ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
    }
    
    // 设置导航栏
    private func prepareNavigationBar() {
    
        // 1. 左侧 关闭
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    
        // 2. 右侧
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        // 右侧默认不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 3. 导航栏
        // 自定义 titleView
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 32))
        
        let label1 = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        label1.text = "发微博"
        label1.sizeToFit()
        let label2 = UILabel(color: UIColor(white: 0.0, alpha: 0.5), fontSize: 13)
        label2.text = sharedUserAccount?.name ?? ""
        
        titleView.addSubview(label1)
        titleView.addSubview(label2)
        label1.ff_AlignInner(ff_AlignType.TopCenter, referView: titleView, size: nil)
        label2.ff_AlignInner(ff_AlignType.BottomCenter, referView: titleView, size: nil)

        navigationItem.titleView = titleView

    }
    
    // MARK: 懒加载
    private lazy var textView = UITextView()
    private lazy var toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: 44))
    private lazy var placeHolderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var lengthLabel = UILabel(color: UIColor.redColor(), fontSize: 12)
    /// 工具栏底部约束
    private var toolBarBottomCons: NSLayoutConstraint?

}
